<?php
/**
 * Created by 王跃达.
 * User: 小马出行
 * Date: 2017/8/25
 * Time: 10:07
 */

namespace my;


class Rsa
{
    const  private_key = '-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCqGF6H0sGIPR3u
ZgRQGP2mHU8hDN+1m7bXw+xveZOttVNxCci6tHRbfaLJ1NwBtQYy1UPzAJukC2EJ
xL7+VdSnYk8/1ehz6aV9aUZUctigr5I/dYUfbM5SOUV4UlkKhzflC2n2A+9UozIE
ZhhlP6TerJ9s61yvVDFz5bsAPZTsac9FaEvbIjLKAHO4wxcyzHj/tb1Pk2oxHC5x
83o0CNtjfAuzkCQ3rxQuCUjKDDZLLTyeSBmE7yjXMgI+WbPqqdKUo7FVxihieg7p
wWLF2WFfaW78NgUWJeQihOygzTlKxy1x305ik3LEsikkc7VkLwebFn7fuvVcZhdJ
WPaI8GltAgMBAAECggEBAImPJbwAdOWCT9eCB5DjdRbHczwOVklgAfHjEC5jC0yb
bTzopb5gvA1VwLYrgDWdOcMYeFhosHZtgW/N/oxfy5gGyIKestwzI9QVtHwNWSYy
dzr9BskQTJdwm78gEcSS8GA659m++unfBU9LZgVUADjZMCF9ArsEgu3w51fddbfu
1HsceVl1pLXMc5eCpoXRhjW3Fg1Ca7hQE1OAfASsAXgf9wljf1hnQHU6Lv6bEASy
qnvXALmlnH/B6XdZ83r1sA7jcDd5loQmCtfIT4VlnptBY4Uf2QzGHOf+TcxAGLJA
XSxg6x29Jk6QKNGdsQppGa32SNcKVBddBB7q++K+nuECgYEA2tzmt4EeIvuVFdPV
1CNKN1MZ8rqlB9QEDUTFPLDAA3UbSq2jVA2TKZOdGkApxresq7Cepn2jPBARb2PS
bif2Go2u0CL7gtIPOhuUIgcCDcUEDi3YEdo3134JsrXbCqOAeILC615zrxCeX53a
ZCUOuXj+UuYRhVl9/g27c+E4htkCgYEAxvURKpoO49c0XpDZHss/6QHKbVNNaCbB
s5pZ9bZx393L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JHO1ZC8HmxZ+37r1XGYXSVj2iPBp
bQIDAQAB
-----END PUBLIC KEY-----
';

    /**
     * 私钥加密
     * @param $string
     * @return string
     */
    public static function privateEncrypt($string){
        $pi_key=openssl_pkey_get_private(self::private_key);
        openssl_private_encrypt($string,$encrypted,$pi_key);//私钥加密
        $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
        return $encrypted;
    }

    /**
     * 公钥解密
     */
    public static function publicDecrypt($string){
        $pu_key=openssl_pkey_get_public(self::public_key);
        openssl_public_decrypt(base64_decode($string),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来
        return $decrypted;
    }


    /**
     * 公钥加密
     */
    public static function publicEncrypt($string){
        $pu_key=openssl_pkey_get_public(self::public_key);
        openssl_public_encrypt($string,$encrypted,$pu_key);//公钥加密
        $encrypted = base64_encode($encrypted);
        return $encrypted;
    }

    /**
     * 私钥解密
     */
    public static function privateDecrypt($string){
        $pi_key=openssl_pkey_get_private(self::private_key);
        openssl_private_decrypt(base64_decode($string),$decrypted,$pi_key);//私钥解密
        return $decrypted;
    }

    /**
     * post参数解密
     */
    public static function postDecode($str){
        $all_post=Rsa::privateDecrypt($str);
        if(empty($all_post)){
            return array("status"=>0);
        }
        $all_arr=explode("&",$all_post);
        foreach($all_arr as $v){
            $val=explode("=",$v);
            $info[$val[0]]=$val[1];
        }
        return array("status"=>1,"data"=>$info);
    }


}